<?php
/**
 * Created by PhpStorm.
 * User: 虚空之翼
 * Date: 2017/4/9
 * Time: 下午5:27
 */

namespace app\index\controller;

use app\common\behavior\Service;
use app\common\model\PayLog;
use app\index\model\ActivityComment;
use app\index\model\ActivityPeople;
use app\index\model\WechatUser;
use think\Config;
use think\Loader;
use think\Log;
use wechat\TPWechat;
use think\Controller;
use app\common\model\ThirdUser as ThirdUserModel;
use app\common\model\PayLog as PayLogModel;
use app\common\model\PointsLog as PointsLogModel;
use EasyWechat\Foundation\Application;
use Hooklife\ThinkphpWechat\Wechat as WechatServer;
use think\Session;
use wxpay\PayNotifyCallBack;

class Wechat extends Controller
{


    public function index()
    {
        phpinfo();
    }

    public function  getJsSdk(){


        $jssdk=  WechatServer::app()->js->config(array('onMenuShareTimeline', 'onMenuShareAppMessage'), true);
        return $jssdk;

    }


    public function callback()
    {
        $weObj = new TPWechat(config('wechat'));
        $weObj->valid();
    }

    public function valid()
    {
        $weObj = new TPWechat(config('scan'));
        $weObj->valid();
    }


    //公众号验证（自定义菜单 ，闭包消息发送去）
    public function serve()
    {
        $server = WechatServer::app()->server;
        $server->serve()->send();
    }


    // 自动登入（微信回调函数）
    public function login()
    {
        $userinfo = WechatServer::app()->oauth->user();
        $reult = $this->_is_subscribe($userinfo->id);
        //关注
        if ($reult == 1) {
            //返回上一个页面
            $this->redirect(session('requestUri'));
        } //未关注
        elseif ($reult == 2) {
            //记录为游客返回上一页
            $this->redirect(session('requestUri'));
            //$this->redirect('http://zyf.0519ztnet.com/index/index/code'); 二维码关注页
        } //报错
        else {
             //TODO  返回报错页
            $this->redirect(session('requestUri'));
        }
    }


    public function _is_subscribe($openid)
    {
        $res = WechatServer::app()->user->get($openid);
        Log::record('_is_subscribe:' . json_encode($res));
        $wechatUser = new WechatUser();
        $result = $wechatUser->where('openid', $openid)->find();
        //已关注
        if ($res['subscribe'] == 1) {
            $data = [
                'openid' => $res['openid'],
                'unionid' => $res['unionid'],
                'nickname' => $res['nickname'],
                'sex' => $res['sex'],
                'city' => $res['city'],
                'province' => $res['province'],
                'country' => $res['country'],
                'language' => $res['language'],
                'headimgurl' => $res['headimgurl'],
                'subscribe_time' => $res['subscribe_time'],
                'unsubscribe_time' => $res['unsubscribe_time'],
                'subscribe' => $res['subscribe'],
                'remark' => $res['remark'],
                'groupid' => $res['groupid'],
                'tagid_list' => json_encode($res['tagid_list']),
            ];
            if ($result) {
                Log::record('update11');
                $wechatUser->where('openid', $openid)->update($data);
            } else {
                Log::record('save');
                $wechatUser->allowField(true)->save($data);
            }
            Session::set('openid', $openid);
            return 1;
        } //未关注
        elseif ($res['subscribe'] == 0) {
           if($result){
               $wechatUser->where('openid', $openid)->update(['subscribe'=>0]);
           }
            Session::set('openid', $openid);
            return 2;

        } else {
            //报错
            return 3;
        }
    }


    /**
     * 微信支付返回
     */
    public function notify()
    {
        //接受成功回调支付信息
        $xml = file_get_contents('php://input');
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
        $xml = '<xml>';
        foreach ($return as $k => $v) {
            $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
        }
        $xml .= '</xml>';
        $map = [
            'status' => 0,
            'out_trade_no' => $arr['out_trade_no'],
        ];
        $paylog_model = new ActivityComment();
        $people_model = new ActivityPeople();
        $res = $paylog_model->where($map)->find();
        if (!$res){
            Log::info($arr['out_trade_no']."--该订单信息不存在");

            return $xml;
        }else{
            $comment_id = $res['id'];
            $people_model->where(['comment_id' => $comment_id])->update(['status' => 2]);
            $update = [
                'jylsh' => $arr['transaction_id'],
                'status' => 1,
                'pay_time' => time(),
            ];
            $result = $paylog_model->where($map)->update($update);
            if ($result){

                return $xml;
            }else{
                Log::info($arr['out_trade_no']."--订单修改失败");

                return $xml;
            }
        }
    }

    /**
     * 微信退款通知地址
     */
    public function refundReturnUrl(){
        //接受成功回调支付信息
        $activity_comment_model = new ActivityComment();
        $xml = file_get_contents('php://input');
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        $configKey = config('wechat')['payment']['key'];
        $key = md5($configKey);
        if ($arr['return_code'] == "SUCCESS"){
            $data = $this->refund_decrypt($arr['req_info'], $key);
            $reqInfo = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            if ($reqInfo['refund_status'] == "SUCCESS"){
                $out_trade_no = $reqInfo['out_trade_no'];
                $map = ['out_trade_no' => $out_trade_no];
                $update = [
                    'status' => 2,
                    'refund_time' => $reqInfo['success_time'],
                    'refund_id' => $reqInfo['refund_id'],
                    'out_refund_no' => $reqInfo['out_refund_no']
                ];
                $result = $activity_comment_model->where($map)->update($update);
                if ($result){

                    return true;
                }else{
                    Log::info("未找到订单信息");

                    return true;
                }

                return false;
            }
        }
    }
    /**
     * AES/ECB/PKCS5Padding 解密
     * @param $str
     * @param $key
     * @return bool|string
     */
    public function refund_decrypt($str, $key) {
        $str = base64_decode($str);
        $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
        $block = mcrypt_get_block_size('rijndael_128', 'ecb');
        $pad = ord($str[($len = strlen($str)) - 1]);
        $len = strlen($str);
        $pad = ord($str[$len - 1]);

        return substr($str, 0, strlen($str) - $pad);
    }
}